/*
 * Copyright (c) 2001, Swedish Institute of Computer Science.
 * All rights reserved. 
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 *
 * 1. Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in the 
 *    documentation and/or other materials provided with the distribution. 
 *
 * 3. Neither the name of the Institute nor the names of its contributors 
 *    may be used to endorse or promote products derived from this software 
 *    without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE. 
 *
 * This file is part of the lwIP TCP/IP stack.
 * 
 * Author: Adam Dunkels <adam@sics.se>
 *
 * $Id: sys.c,v 1.4 2001/01/31 09:11:46 adam Exp $
 */

#include "debug.h"

#include <errno.h>
#include <strings.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "sys.h"
#include "dlist.h"

#define UMAX(a, b)      ((a) > (b) ? (a) : (b))

/*static struct irq_s *irqs;*/
/*static struct dlist *timeouts;*/
static struct sys_thread *threads = NULL;

struct timeout_s {
  sys_timeout_handler h;
  void *data;
};

struct sys_mbox_msg {
  struct sys_mbox_msg *next;
  void *data;
};

struct sys_mbox {
  struct sys_sem *mail, *fetch;
  struct sys_sem *mutex;
  struct sys_mbox_msg *msgs;
};

struct sys_sem {
  unsigned int c;
  pthread_cond_t cond;
  pthread_mutex_t mutex;
};

struct irq_s {
  struct irq_s *next;
  sys_irq_handler h;
  int fd;
  void *data;
};


struct sys_thread {
  struct sys_thread *next;
  struct dlist *timeouts;
  struct irq_s * irqs;
  pthread_t pthread;
};


static struct timeval starttime;
/*-----------------------------------------------------------------------------------*/
static struct sys_thread *
current_thread(void)
{
  struct sys_thread *st;
  pthread_t pt;
  pt = pthread_self();
  /*  DEBUGF("sys: current_thread: pt %d\n", pt);*/
  for(st = threads; st != NULL; st = st->next) {
    /*    DEBUGF("sys: current_thread: st->pthread %d\n", st->pthread);*/
    if(pthread_equal(st->pthread, pt)) {
      return st;
    }
  }
  printf("sys: current_thread: could not find current thread!\n");
  printf("This is due to a race condition in the LinuxThreads\n");
  printf("pthreads implementation. Start the program again.\n");
  

  abort();
}
/*-----------------------------------------------------------------------------------*/
struct sys_thread *
sys_thread_new(void *(* function)(void *arg), void *arg)
{
  struct sys_thread *thread;
  thread = malloc(sizeof(struct sys_thread));
  thread->next = threads;
  thread->timeouts = dlist_new();
  thread->irqs = NULL;
  threads = thread;

  if(pthread_create(&(thread->pthread), NULL, function, arg) != 0) {
    perror("sys_thread_new: pthread_create");
    abort();
  }
  return thread;
}
/*-----------------------------------------------------------------------------------*/
struct sys_mbox *
sys_mbox_new()
{
  struct sys_mbox *mbox;

  mbox = malloc(sizeof(struct sys_mbox));
  mbox->mail = sys_sem_new(0);
  mbox->fetch = sys_sem_new(0);
  mbox->mutex = sys_sem_new(1);
  mbox->msgs = NULL;
  /*  DEBUGF("sys_mbox_new: mbox 0x%lx\n", mbox); */
  return mbox;
}
/*-----------------------------------------------------------------------------------*/
void
sys_mbox_free(struct sys_mbox *mbox)
{
  struct sys_mbox_msg *msg, *nmsg;
  
  /*  DEBUGF("sys_mbox_free: 0x%lx before wait(fetched)\n", (long)mbox);*/

  if(mbox == NULL) {
    return;
  }
  sys_sem_wait(mbox->mutex);
  
  msg = mbox->msgs;
  while(msg != NULL) {
    nmsg = msg->next;
    free(msg);
    msg = nmsg;
  }
  mbox->msgs = NULL;
  sys_sem_free(mbox->mail);
  sys_sem_free(mbox->fetch);
  mbox->mail = mbox->fetch = NULL;
  /*  DEBUGF("sys_mbox_free: mbox 0x%lx\n", mbox);*/
  free(mbox);
}
/*-----------------------------------------------------------------------------------*/
void
sys_mbox_post(struct sys_mbox *mbox, void *data)
{
  struct sys_mbox_msg *msg, *imsg;

  sys_sem_wait(mbox->mutex);
  
  /*  DEBUGF("sys_mbox_post: 0x%lx\n", mbox);*/
  /*  sys_sem_wait(mbox->mail);*/

  msg = malloc(sizeof(struct sys_mbox_msg));
  msg->next = NULL;
  msg->data = data;
  if(mbox->msgs == NULL) {
    mbox->msgs = msg;
    sys_sem_signal(mbox->mail);
  } else {
    for(imsg = mbox->msgs; imsg->next != NULL; imsg = imsg->next);
    imsg->next = msg;
  }
  /*  sys_sem_signal(mbox->fetch);*/

  sys_sem_signal(mbox->mutex);
}
/*-----------------------------------------------------------------------------------*/
void
sys_mbox_fetch(struct sys_mbox *mbox, void **data)
{
  struct sys_mbox_msg *msg;

  sys_sem_wait(mbox->mutex);
  
  /*  sys_sem_wait(mbox->fetch);*/

  while(mbox->msgs == NULL) {
    sys_sem_signal(mbox->mutex);
    sys_sem_wait(mbox->mail);
    sys_sem_wait(mbox->mutex);
  }
  *data = mbox->msgs->data;
  msg = mbox->msgs->next;
  free(mbox->msgs);
  mbox->msgs = msg;
  /*  sys_sem_signal(mbox->mail);*/

  sys_sem_signal(mbox->mutex);
}
/*-----------------------------------------------------------------------------------*/
struct sys_sem *
sys_sem_new(int count)
{
  struct sys_sem *sem;
  /*  pthread_mutexattr_t attr;*/
  
  sem = malloc(sizeof(struct sys_sem));
  sem->c = count;

  /*  pthread_mutexattr_init(&attr);
      pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP);*/
  
  pthread_cond_init(&(sem->cond), NULL);
  /*  pthread_mutex_init(&(sem->mutex), &attr);*/
  pthread_mutex_init(&(sem->mutex), NULL);
  return sem;
}
/*-----------------------------------------------------------------------------------*/
static void
cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
  unsigned int time, tdiff;
  unsigned long sec, usec;
  struct sys_thread *thread;
  struct dlist *timeouts;
  struct timeout_s *timeout_s;
  struct timeval rtime1, rtime2;
  struct timespec ts;
  struct timezone tz;
  int retval;

  thread = current_thread();
  timeouts = thread->timeouts;
  
  if(dlist_is_empty(timeouts)) {
    pthread_cond_wait(cond, mutex);
  } else {
    time = dlist_first(timeouts, (void **)&timeout_s);
    
    /* Get a timestamp. */
    gettimeofday(&rtime1, &tz);
    sec = rtime1.tv_sec;
    usec = rtime1.tv_usec;
    usec += time % 1000 * 1000;
    sec += (int)(time / 1000) + (int)(usec / 1000000);
    usec = usec % 1000000;
    ts.tv_nsec = usec * 1000;
    ts.tv_sec = sec;

    retval = pthread_cond_timedwait(cond, mutex, &ts);
    if(retval == ETIMEDOUT) {
      /* timeout occured */
      do {
        timeout_s = dlist_remove_first(timeouts);
        timeout_s->h(timeout_s->data);
        free(timeout_s);
	if(!dlist_is_empty(timeouts)) {
	  time = dlist_first(timeouts, (void **)&timeout_s);
	}
      } while(!dlist_is_empty(timeouts) && time == 0);      

    } else {
      
      /* Calculate for how long we waited for the cond. */
      gettimeofday(&rtime2, &tz);
      tdiff = (rtime2.tv_sec - rtime1.tv_sec) * 1000 +
	(rtime2.tv_usec - rtime1.tv_usec) / 1000;
      
      /* Reschedule the first timeout on the list. */
      if(!dlist_is_empty(timeouts)) {
	time = dlist_first(timeouts, (void **)&timeout_s);
	if((signed long)time - (signed long)tdiff < 0) {
	  time = 0;
	} else {
	  time -= tdiff;
	}
	dlist_update_first(timeouts, time);
      }
    }
  }
}
/*-----------------------------------------------------------------------------------*/
void
sys_sem_wait(struct sys_sem *sem)
{
  pthread_mutex_lock(&(sem->mutex));
  while(sem->c <= 0) {
    cond_wait(&(sem->cond), &(sem->mutex));
  }
  sem->c--;
  pthread_mutex_unlock(&(sem->mutex));
}
/*-----------------------------------------------------------------------------------*/
void
sys_sem_signal(struct sys_sem *sem)
{
  pthread_mutex_lock(&(sem->mutex));
  sem->c++;
  pthread_mutex_unlock(&(sem->mutex));
  pthread_cond_signal(&(sem->cond));
}
/*-----------------------------------------------------------------------------------*/
void
sys_sem_free(struct sys_sem *sem)
{
  pthread_cond_destroy(&(sem->cond));
  pthread_mutex_destroy(&(sem->mutex));
  free(sem);
}
/*-----------------------------------------------------------------------------------*/
unsigned long
sys_now()
{
  struct timeval tv;
  struct timezone tz;
  long sec, usec;
  unsigned long msec;
  gettimeofday(&tv, &tz);

  sec = tv.tv_sec - starttime.tv_sec;
  usec = tv.tv_usec - starttime.tv_usec;
  msec = sec * 1000 + usec / 1000;
  return msec;
}
/*-----------------------------------------------------------------------------------*/
void
sys_irq(int fd, sys_irq_handler h, void *data)
{
  struct sys_thread *thread;
  struct irq_s *i;

  thread = current_thread();
  
  i = malloc(sizeof(struct irq_s));
  i->fd = fd;
  i->h = h;
  i->data = data;
  i->next = thread->irqs;
  thread->irqs = i;
}
/*-----------------------------------------------------------------------------------*/
void
sys_timeout(unsigned int msecs, sys_timeout_handler h, void *data)
{
  struct timeout_s *t;
  struct dlist *timeouts;
  struct sys_thread *thread;
  
  thread = current_thread();
  timeouts = thread->timeouts;
  
  t = malloc(sizeof(struct timeout_s));
  t->h = h;
  t->data = data;
  dlist_insert(timeouts, t, msecs);
  DEBUGF(SYS_DEBUG, ("sys_timeout: %u msecs (%p)\n", msecs, (void *)t));
}
/*-----------------------------------------------------------------------------------*/
void
sys_init()
{
  struct timezone tz;
  gettimeofday(&starttime, &tz);
}

/*-----------------------------------------------------------------------------------*/
void
sys_main()
{
  int max_desc, retval, tdiff;
  fd_set fdset;     
  struct timeval tv, rtime1, rtime2;
  struct timezone tz;
  struct irq_s *irq;
  struct timeout_s *timeout_s;
  int time;
  struct dlist *timeouts;
  struct sys_thread *thread;


  thread = current_thread();
  timeouts = thread->timeouts;

  /* check for timeouts */
  
  /* time == -1 signals no timeout */
  time = -1;
  if(!dlist_is_empty(timeouts)) {
    time = dlist_first(timeouts, (void **)&timeout_s);
  }
  

  while(1) {

    FD_ZERO(&fdset);
    max_desc = 0;

    /* check for registered irqs */

    for(irq = thread->irqs; irq != NULL; irq = irq->next) {
      FD_SET(irq->fd, &fdset);                 
      max_desc = UMAX(max_desc, irq->fd);      
    }

    
    /* wait for arriving network data or until some time event occurs */
    gettimeofday(&rtime1, &tz);
   
    if(time >= 0) {
      tv.tv_sec = time / 1000;
      tv.tv_usec = (time % 1000) * 1000;
      retval = select(max_desc + 1, &fdset, NULL, NULL, &tv);
    } else {
      retval = select(max_desc + 1, &fdset, NULL, NULL, NULL);
    }
    if(retval == 0) {
      /* timeout occured */
      timeout_s = dlist_remove_first(timeouts);
      /*      DEBUGF("sys: timeout %d\n", timeout_s->id);*/
      timeout_s->h(timeout_s->data);
      free(timeout_s);
      /* schedule new timeout */
      time = -1;
      if(!dlist_is_empty(timeouts)) {
	time = dlist_first(timeouts, (void **)&timeout_s);
      }
    } else {
      /* Something happened on the file descriptors. */
      if(time >= 0) {
	gettimeofday(&rtime2, &tz);
	tdiff = (rtime2.tv_sec - rtime1.tv_sec) * 1000000 +
	  rtime2.tv_usec - rtime1.tv_usec;
	time -= tdiff;
	if(time < 0) {
	  time = 0;
	}
	  
      }
      if(retval > 0) {
	for(irq = thread->irqs; irq != NULL; irq = irq->next) {
	  if(FD_ISSET(irq->fd, &fdset)) {
	    irq->h(irq->fd, irq->data);	      
	  }
	}	
      } else {
	perror("sys_main: select");
	abort();
      }
    }
  }

}
/*-----------------------------------------------------------------------------------*/







